﻿package com.rbac.system.service.impl;

import com.rbac.system.entity.Permission;
import com.rbac.system.entity.Role;
import com.rbac.system.entity.RolePermission;
import com.rbac.system.entity.UserRole;
import com.rbac.system.mapper.PermissionMapper;
import com.rbac.system.mapper.RoleMapper;
import com.rbac.system.mapper.RolePermissionMapper;
import com.rbac.system.mapper.UserRoleMapper;
import com.rbac.system.service.PermissionInitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 权限初始化服务实现
 */
@Service
public class PermissionInitServiceImpl implements PermissionInitService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Override
    @Transactional
    public void initializeBasicPermissions() {
        // 创建基础权限
        createPermissionIfNotExists("user:profile:view", "查看个人信息", "OPERATION", 0L, "查看用户个人信息权限");
        createPermissionIfNotExists("user:profile:edit", "编辑个人信息", "OPERATION", 0L, "编辑用户个人信息权限");
        createPermissionIfNotExists("user:password:change", "修改密码", "OPERATION", 0L, "修改用户密码权限");
        
        // 创建基础角色
        createRoleIfNotExists("USER", "普通用户", "系统普通用户角色");
        
        // 为普通用户角色分配基础权限
        assignBasicPermissionsToUserRole();
    }
    
    @Override
    @Transactional
    public void createBasicUserPermissions(Long userId) {
        // 检查用户是否已有角色
        List<UserRole> userRoles = userRoleMapper.selectByUserId(userId);
        
        if (userRoles.isEmpty()) {
            // 为新用户分配普通用户角色
            Role userRole = roleMapper.selectByRoleCode("USER");
            if (userRole != null) {
                UserRole newUserRole = new UserRole();
                newUserRole.setUserId(userId);
                newUserRole.setRoleId(userRole.getId());
                newUserRole.setCreateTime(LocalDateTime.now());
                newUserRole.setDeleted(0);
                userRoleMapper.insert(newUserRole);
            }
        }
    }
    
    @Override
    public void checkAndCreateMissingPermissions() {
        // 只检查和创建最基础的权限，不创建角色
        createPermissionIfNotExists("user:profile:view", "查看个人信息", "OPERATION", 0L, "查看用户个人信息权限");
        createPermissionIfNotExists("user:profile:edit", "编辑个人信息", "OPERATION", 0L, "编辑用户个人信息权限");
        createPermissionIfNotExists("user:password:change", "修改密码", "OPERATION", 0L, "修改用户密码权限");

        // 检查通知管理相关权限
        createPermissionIfNotExists("notice:list", "查看通知列表", "OPERATION", 0L, "查看通知公告列表权限");
        createPermissionIfNotExists("notice:view", "查看通知详情", "OPERATION", 0L, "查看通知公告详情权限");
        createPermissionIfNotExists("notice:add", "添加通知", "OPERATION", 0L, "添加通知公告权限");
        createPermissionIfNotExists("notice:update", "编辑通知", "OPERATION", 0L, "编辑通知公告权限");
        createPermissionIfNotExists("notice:delete", "删除通知", "OPERATION", 0L, "删除通知公告权限");
        createPermissionIfNotExists("notice:publish", "发布通知", "OPERATION", 0L, "发布通知公告权限");
    }
    
    /**
     * 创建权限（如果不存在）
     */
    private void createPermissionIfNotExists(String permissionCode, String permissionName, 
                                           String permissionType, Long parentId, String description) {
        Permission existingPermission = permissionMapper.selectByCode(permissionCode);
        if (existingPermission == null) {
            Permission permission = new Permission();
            permission.setPermissionCode(permissionCode);
            permission.setPermissionName(permissionName);
            permission.setPermissionType(permissionType);
            permission.setParentId(parentId);
            permission.setDescription(description);
            permission.setSort(0);
            permission.setStatus(1);
            permission.setCreateTime(LocalDateTime.now());
            permission.setUpdateTime(LocalDateTime.now());
            permission.setDeleted(0);
            
            permissionMapper.insert(permission);
        }
    }
    
    /**
     * 创建角色（如果不存在）
     */
    private void createRoleIfNotExists(String roleCode, String roleName, String description) {
        Role existingRole = roleMapper.selectByRoleCode(roleCode);
        if (existingRole == null) {
            Role role = new Role();
            role.setRoleCode(roleCode);
            role.setRoleName(roleName);
            role.setDescription(description);
            role.setStatus(1);
            role.setCreateTime(LocalDateTime.now());
            role.setUpdateTime(LocalDateTime.now());
            role.setDeleted(0);
            
            roleMapper.insert(role);
        }
    }
    
    /**
     * 为普通用户角色分配基础权限
     */
    private void assignBasicPermissionsToUserRole() {
        Role userRole = roleMapper.selectByRoleCode("USER");
        if (userRole == null) {
            return;
        }
        
        // 基础权限编码列表
        List<String> basicPermissionCodes = Arrays.asList(
            "user:profile:view",
            "user:profile:edit", 
            "user:password:change"
        );
        
        for (String permissionCode : basicPermissionCodes) {
            Permission permission = permissionMapper.selectByCode(permissionCode);
            if (permission != null) {
                // 检查角色权限关联是否已存在
                List<RolePermission> existingRolePermissions = rolePermissionMapper.selectByRoleId(userRole.getId());
                boolean hasPermission = existingRolePermissions.stream()
                    .anyMatch(rp -> rp.getPermissionId().equals(permission.getId()));
                
                if (!hasPermission) {
                    RolePermission rolePermission = new RolePermission();
                    rolePermission.setRoleId(userRole.getId());
                    rolePermission.setPermissionId(permission.getId());
                    rolePermission.setCreateTime(LocalDateTime.now());
                    rolePermission.setDeleted(0);
                    rolePermissionMapper.insert(rolePermission);
                }
            }
        }
    }
}


